// 新增或者编辑组件
<template>
  <el-dialog title="表单"
             :visible.sync="addEditDialogShow"
             @close="closeAddEditDialog"
             width="65%">
    <span slot="title">
      <span>{{addEditData===undefined?'新增':'编辑'}}</span>
    </span>
    <hr style="margin-top:0px">
    <el-form :model="formData"
             ref="formRef"
             :inline="true"
             size="mini"
             label-position="right"
             label-width="100px">
      <el-form-item v-for="(item, index) in getFormOptions"
                    :key="newKeys[index]"
                    :prop="item.prop"
                    :label="$t(item.label) ? ($t(item.label) + '：') : ''"
                    :rules="item.rules">
        <formItem v-model="formData[item.prop]"
                  :itemOptions="item" />
      </el-form-item>
      <!-- 自定义插槽，可用于特殊表单块 -->
      <slot></slot>
    </el-form>
    <span slot="footer">
      <hr>
      <el-button @click="onReset()"
                 size="mini">清空</el-button>
      <el-button type="primary"
                 size="mini"
                 @click="queryOk()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import formItem from './add-edit-form.vue'
import { createUniqueString } from '../search/tools'
export default {
  components: { formItem },
  props: {
    formOptions: {
      type: Array,
      required: true,
      default () {
        return []
      }
    },
    // 是否展示新增编辑表单
    addEditDialogShow: Boolean,
    // 是否清空查询条件的表单数据
    clearQueryForm: Boolean,
    // 需要编辑的数据
    addEditData: Object
  },
  data () {
    return {
      // 表单数据
      formData: {},
      showAddEditDialog: false
    }
  },
  watch: {
    // // 查询框的状态改变
    // searchDialog (newVal) {
    //   this.showSearchDialog = newVal
    // },
    // // 清空查询条件的表单数据
    // clearQueryForm (newVal) {
    //   if (newVal) {
    //     this.formData = {}
    //   }
    // }
  },
  computed: {
    newKeys () {
      return this.formOptions.map(v => {
        return createUniqueString()
      })
    },
    getFormOptions () {
      this.addInitValue()
      return this.formOptions
    }
  },
  created () {

  },
  mounted () {
  },
  methods: {
    // 表单重置
    onReset () {
      this.$refs.formRef.resetFields()
    },
    // 确认提交
    queryOk () {
      this.$emit('addEditOk', this.formData)
    },
    // 添加初始值
    addInitValue () {
      const obj = {}
      this.formOptions.forEach(v => {
        if (v.initValue !== undefined && v.initValue !== null) {
          obj[v.prop] = v.initValue
        }
      })
      this.formData = obj
    },
    // 关闭查询条件框
    closeAddEditDialog () {
      this.$emit('controlAddEditDialog', false)
    }
  }
}
</script>

<style >
.el-dialog__body {
  padding: 0px 0px;
}
.el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
</style>
